#!/usr/bin/env -S node -r ./livescript-transform-implicit-async/register

require! <[
  ./argv.ls
  chalk
  crypto
  file-trace
  path
  pug
  terser
]>

require! {
  \fs-extra : fs
}

module.exports = !~>
  cwd = argv.cwd
  trace = file-trace(cwd).trace!
  if await trace.cached!
    return

  config = await trace.read-yaml(\6du/html)

  _todo = []
  _await = (p)!~>
    _todo.push p

  render = (filename, option={})~>>
      pug.render(
        await trace.read("6du/#filename.pug")
        {
          C:option<<<config
        }
      )

  config.pug = {}
  for template in <[aside foot]>
    config.pug[template] = await render(template)

  _6_js = "6.js"
  js = """C=#{JSON.stringify(config)};#{await trace.read('6du/'+_6_js)}"""
  console.log chalk.gray "生成 #_6_js"
  _await fs.write-file(
    path.join(cwd, _6_js)
    terser.minify(js).code
  )

  sw-js = \sw.js
  _await trace.write(
    sw-js
    terser.minify(
      "(()=>{#{await trace.read path.join \6du,sw-js}})()"
    ).code.slice(6,-5)
  )
  html = await render(
    'index'
    * hash : crypto
          .createHash('sha256')
          .update(js, 'utf8')
          .digest(\base64).slice(0,-1)
  )
  _await trace.write(\index.html, html)
  _await trace.write(\404.html, html)
  await _todo
  process.on-exit !~>
    await trace.read(_6_js)
    await trace.save!

if require.main == module
  do !~>
    await module.exports!

